local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.Server_PlayerComponent(),script.Parent.Name);
local EventList = ServerOHOH.load.EventList();

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);
    self.player=self.parent

    self.playerRemoveConnect= game.Players.PlayerRemoving:Connect(function(player)
        print("————————————————玩家离开————————————————————")
        self.Car.battleEnd = true
    end)
end;

function M.dtor(self)

    self:ClearLevelTrack()
	M.super.dtor(self);
end;


function M.ClearLevelTrack(self)
    if self.ActiveLevel then
        self.ActiveLevel:dtor()
        self.ActiveLevel=nil
    end

    if self.Car then
        self.Car:dtor()
        self.Car=nil
    end

end

-- 创建一局比赛
function M.CreateLevelTrack(self,levelId)
    print("********  创建一局比赛 ***************")
    self:ClearLevelTrack()
    
    self.Car=_G.CommonOHOH.load.LevelCar().new(self.player)

    -- local data={}
	-- for i=1,100 do
	-- 	table.insert(data,math.random(1,6))
	-- end
    

    self.ActiveLevel=_G.CommonOHOH.load.Level().new(levelId)

    self.parent.character:SetCFrame(self.ActiveLevel:GetCarInitCFrame())
    self.Car:SetCFrame(self.ActiveLevel:GetCarInitCFrame())

    self.Car:SetParent(workspace)

    
    task.wait()
    self.Car:CustomDrive()--使用humanoid
    self.Car:Start(self.ActiveLevel:GetOrbit():FindFirstChild("StartPlatform"):FindFirstChild("Points")) --开始一局

    self.Car.GetRewardEvent:Connect(function(key,value)
       if value then
        --加矿石带来的钻石
            self.parent:GetComponent(ServerOHOH.load.Server_ItemCtrl()):AddItem({[key]=value},true,true)
         --ui显示砖石数量 
            self:Fire(EventList.get_reward,key,value)
       else
        --加宝箱带来的Buff
        print("宝箱——————————————",key,value)
            if not self.BuffCtrl then
                self.BuffCtrl = self.player:GetComponent(_G.CommonOHOH.load.Common_BuffCtrl())
            end
            value = 1
            self:Fire(EventList.get_reward,key,value)
            self.parent:GetComponent(ServerOHOH.load.Server_ItemCtrl()):AddItem({[key]=1},true,true)
        --ui显示物品数量  （待实现）需要在Asset表配置相关物品 并将 value = 1
        --value = 1
        end
      
    end)
    -- self:AddProcess(function()
    --     self.Car:AddCharacter(self.player.character.main_inst)
    --     self:Wait(1)
    --     self.Car:AnchoredSwitch(false)
    --     self:Wait(0.5)
    --     self.Car:SetForwardSpeed(-50)
    --     self.Car:SetDrillingSpeed(10)

        
    -- end)


    -- self.ActiveLevel.ExitEvent:Connect(function()
    --     self:ClearTrack()
    -- end)
    
    -- self.ActiveLevel.PassEvent:Connect(function()
    --     self:ClearTrack()
    -- end)

    -- self.ActiveLevel.FailEvent:Connect(function()
    --     self:ClearTrack()
    -- end)


end


return M